<?php

class BrowserController extends Controller
{
    public $layout = 'index';
	public function actionDetail()
	{
		$this->render('Detail');
	}

	public function actionError()
	{
		$this->render('Error');
	}

	public function actionInfo()
	{
		$this->render('Info');
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;
		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
		  	$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
			    Yii::app()->user->setId($model->email);
			    if(!User::model()->lastLogin($model->email)){
                   throw new CHttpException(404,'Cập nhật truy cập lần cuối thất bại');
			    }
                $this->redirect(array('ProductAdmin/Index'));
            }
		}
		// display the login form
		$this->render('Login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->user->loginUrl);
	} 
    
    /**
     * Change password
    */
    public function actionchangePassword(){
        $model=$this->loadModel(User::model()->getId(Yii::app()->user->getId()));
        if(isset($_POST['User'])){
            $model->attributes=$_POST['User'];
            if($model->validate()){
                $old_pass=User::getPassword();
                $new_pass=md5($model->new_password);
                if($old_pass==md5($model->old_password)){
                    $model->password=md5($model->new_password);
                    if($model->save(true,'password')){
                        $this->redirect(array('userAdmin/changePassword','status'=>1));
                    }else{
                        $this->redirect(array('userAdmin/changePassword','status'=>0));
                    }
                }else{
                    $this->redirect(DOMAIN);
                    //$this->redirect(array('userAdmin/changePassword','status'=>2));
                }
            }
        }
        $this->render('changePassword',array('model'=>$model));
    }
    
    public function actionForgotPassword()
	{
		$this->render('ForgotPassword');
	}

	public function actionSearch()
	{
		$this->render('Search');
	}

    /**
	 * Displays the contact page
	 */
	public function actionSignup()
	{
		$model=new User;
		if(isset($_POST['User']))
		{
		    $model->attributes=$_POST['User'];
			if($model->validate(array('email','new_password','firstname','lastname'))){
			     $model->password=md5($model->new_password);
                 if($model->save(true,array('email','password','firstname','lastname'))){
                    if (isset($_POST['is_subscribed'])) {
                        Subscription::model()->addSubscriptor($model->email);
                    }
                    $this->render('Signup',array('model'=>$model,'status'=>'success'));   
			     }else{
			         throw new CHttpException(404,'Đăng ký thành viên thất bại');
			     }
			}
		}
		$this->render('Signup',array('model'=>$model));
	}

	public function actionTags()
	{
		$this->render('Tags');
	}

	public function actionViewBy()
	{
	    if(isset($_GET['category_id'])&&is_numeric($_GET['category_id'])){
	        $category_id=$_GET['category_id'];
            if(isset($conditions)){
                $conditions=$conditions." AND category_id=".$category_id;
            }else{
                $conditions="category_id=".$category_id;
            }
	    }
        if(isset($_GET['brand_id'])&&is_numeric($_GET['brand_id'])){
            $brand_id=$_GET['brand_id'];
            if(isset($conditions)){
                $conditions=$conditions." AND brand_id=".$brand_id;
            }else{
                $conditions="brand_id=".$brand_id;
            }
        }
        
        //price range
        if(isset($_GET['range'])&&is_numeric($_GET['range'])){
            $price=$_GET['range'];
            if ($price==1) {
            	if(isset($conditions)){
            	   $conditions=$conditions." AND product_price<=1000000";
            	}else{
            	   $conditions="product_price<=1000000";
            	}
            }elseif($price==2){
                if(isset($conditions)){
            	   $conditions=$conditions." AND product_price>1000000 AND product_price<=3000000";
            	}else{
            	   $conditions="product_price>1000000 AND product_price<=3000000";
            	}
            }elseif($price==3){
                if(isset($conditions)){
            	   $conditions=$conditions." AND product_price>3000000 AND product_price<=5000000";
            	}else{
            	   $conditions="product_price>3000000 AND product_price<=5000000";
            	}
            }elseif($price==4){
                if(isset($conditions)){
            	   $conditions=$conditions." AND product_price>5000000 AND product_price<=10000000";
            	}else{
            	   $conditions="product_price>5000000 AND product_price<=10000000";
            	}
            }elseif($price==5){
                if(isset($conditions)){
            	   $conditions=$conditions." AND product_price>10000000";
            	}else{
            	   $conditions="product_price>10000000";
            	}
            }
        }
        
        if(!isset($conditions)){
            $conditions="";
        }
        
	    //kiểu hiển thị grid hay list   
        if(isset($_GET['mode'])&&$_GET['mode']=="list"){
            $mode='List';    
        }else{
            $mode='Grid';
        }
        //giới hạn sản phẩm/trang (phân trang)
        if(isset($_GET['limit'])&&is_numeric($_GET['limit'])&&$_GET['limit']>=6){
            $limit=$_GET['limit'];
        }else{
            $limit=Yii::app()->params['itemsPerPage'];
        }
        
        //sắp xếp theo tên, giá hay mặc định là thời gian cập nhật
        if(isset($_GET['order'])&&$_GET['order']=="name"){
            $orderby='product_name';
        }elseif(isset($_GET['order'])&&$_GET['order']=="price"){
            $orderby='product_price';
        }else{
            $orderby='product_timeupdate';
        }
        //sắp xếp tăng hay giảm?
        if(isset($_GET['dir'])&&$_GET['dir']=="asc"){
            $dir=' asc';
        }else{
            $dir=' desc';
        }
        
        //paging
        $totalItems=Product::model()->findAll($conditions);
        $pages=new CPagination(count($totalItems));
        $pages->setPageSize($limit);
        
        if(isset($_GET['page'])&&is_numeric($_GET['page'])){
            $page=$_GET['page'];
            if($page<=0){
                $page=0;
            }elseif($page>=$pages->getPageCount()){
                $page=$pages->getPageCount()-1;
            }else{
                $page=$_GET['page']-1;
            }
        }elseif(!isset($_GET['page'])){
            $page=0;
        }else{
            throw new CHttpException(404,'Không tồn tại trang');
        }
        
        $pages->setCurrentPage($page);
        $offset=$pages->getOffset();
        $limit=$pages->getLimit();
        
        $critera=new CDbCriteria(array(
            'condition'=>$conditions,
            'order'=>$orderby.$dir,
            'offset'=>$offset,
            'limit'=>$limit,
        ));
        
        $dataProvider=new CActiveDataProvider('Product', array(
            'criteria'=>$critera,
            'pagination'=>false,
        ));
        
        $this->render('ViewBy'.$mode,array('model'=>$dataProvider->getData(),'pages'=>$pages));
	}
    
    public function actionAddToCart(){
        $this->render('AddToCart');
    }
    
    public function actionCompareProduct(){
        $this->render('CompareProduct');
    }
    
    public function actionContact(){
        $this->render('Contact');
    }
    
    public function actionSiteMap(){
        if(isset($_GET['sitemap'])&&$_GET['sitemap']=='pro'){
            $sitemap='Pro';
        }else{
            $sitemap='Cat';
        }
        $this->render('SiteMap'.$sitemap);
    }

	public function actionIndex()
	{
		$this->render('index');
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}